package main

import (
	"strconv"
	"strings"
)

//func main() {
//	l1 := createListNode([]int{9, 9, 9, 9, 9, 9, 9})
//	l2 := createListNode([]int{9, 9, 9, 9})
//
//	result := addTwoNumbers(l1, l2)
//
//	println(result.toString())
//}

type ListNode struct {
	Val  int
	Next *ListNode
}

func createListNode(arr []int) *ListNode {
	head := &ListNode{}
	temp := head

	for _, i := range arr {
		temp.Next = &ListNode{i, nil}
		temp = temp.Next
	}
	return head.Next
}

func (list *ListNode) toString() string {
	builder := strings.Builder{}
	builder.WriteString(strconv.Itoa(list.Val))

	item := list
	for item.Next != nil {
		item = item.Next
		builder.WriteString(" -> ")
		builder.WriteString(strconv.Itoa(item.Val))
	}
	return builder.String()
}

func addTwoNumbers(l1, l2 *ListNode) *ListNode {
	var r int
	carry := 0
	temp := &ListNode{-1, nil}
	result := temp
	n1, n2 := 0, 0

	for l1 != nil || l2 != nil {
		n1, n2 = 0, 0
		if l1 != nil {
			n1 = l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			n2 = l2.Val
			l2 = l2.Next
		}
		r = n1 + n2 + carry
		r, carry = r%10, r/10

		temp.Next = &ListNode{r, nil}
		temp = temp.Next
	}
	if carry > 0 {
		temp.Next = &ListNode{carry, nil}
	}

	return result.Next
}
